import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Common {

	static SimpleDateFormat fmt0 = new SimpleDateFormat("yyyyMMdd");
	static SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");

	public static String file_to_save = "";

	public static String getTimeString() {
		return fmt1.format(new Date());
	}

	public static boolean appendToFile(String datetime, int test_id, String type, String item, long size, double time,
			String infile) throws Exception {
		double second = time / 1_000_000_000.0;
		String info = String.format("%s,%02d,%s,%s,%012d,%.6f,%012.0f,%s\n", // 格式化为统一的CSV字符串
				datetime, // 发生时间
				test_id, // 第几次测试
				type, // 类型 hse_en=加密，hse_de=解密，ase_en=加密，aes_de=解密；
				item, // 项目名称
				size, // 文件大小，单位为 byte
				second, // 输入时间单位为ms
				size / second, // 转换速度，单位为 byte/ms
				infile // 输出文件
		);
		File file = new File(file_to_save);
		if (!file.exists()) {
			// System.out.println("create result.csv at: " + file_to_save);
			file.createNewFile();
			appendToFile(file.getAbsolutePath(), "time,ordinal,type,command,size,duration,speed,fullpath\n");
		}
		appendToFile(file.getAbsolutePath(), info);
		Thread.sleep(1);
		return true;
	}

	public static void appendToFile(String filepath, String content) throws IOException {
		System.out.print(content);
		FileWriter writer = new FileWriter(filepath, true);
		writer.write(content);
		writer.close();
	}

	public static void deleteFiles(String dir) {
		File directory = new File(dir);
		File[] files = directory.listFiles();
		// 遍历每个文件对象并删除
		for (File file : files) {
			if (file.isFile()) { // 只删除文件，不删除目录
				if (!file.delete())
					System.out.printf("Failed to delete '%s'.\n", file.getAbsoluteFile());
			}
		}
	}

	public static void printArgs(String[] args) {
		System.out.println("---------------------- Argument list------------------------");
		for (int i = 0; i < args.length; i++) {
			System.out.printf("args[%d]:\t%s\n", i, args[i]);
		}
		System.out.println("------------------------------------------------------------");
	}
}
